package com.hylanda.pb.controller;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hylanda.pb.model.ReportModel;
import com.hylanda.pb.service.PBAppService;
import com.hylanda.pb.service.PowerBiService;
import com.hylanda.pb.service.PowerBiTokenService;
/** 
 * @author zhangy
 * @E-mail:blackoon88@gmail.com 
 * @qq:846579287
 * @version created at：2018年3月2日 上午9:53:25 
 * note
 */
@Controller
@RequestMapping("/reportmodel")
public class PBAppController {
	@Autowired
	private PBAppService reportModelService;
	@Autowired
	private PowerBiTokenService powerBiTokenService;
	@Autowired
	private PowerBiService powerBiService;
	private static Logger logger = LoggerFactory.getLogger(PBAppController.class);
//  private static final String apitokenHeader = "eyJhbGciOiJIUzI1NiJ9.";
	@RequestMapping(value={"/get/{instanceId}/{savePolicy}/{apitoken}"}, method={RequestMethod.GET})
	  public String getPowerbiHtml3(HttpServletRequest request, HttpServletResponse response, @PathVariable("instanceId") String instanceId
			  ,@PathVariable("savePolicy") String savePolicy,
			  @PathVariable("apitoken") String apitoken ,ModelMap mode)
	  {
	    apitoken =apitoken.replace("@", ".");
	    logger.info("nifitoken:"+apitoken);
	    boolean isValid = this.powerBiTokenService.isValid(apitoken);
	    if (!isValid) {
	      mode.put("info", "请联系管理员，请求会话过期");
	      return "error";
	    }
	    
	    Map<String, Object> map = this.reportModelService.getReportModelByInstanceId(instanceId);
	 
	    if (map == null) {
	      mode.put("info", "请联系管理员，输入的instanceID没找到相应的记录");
	      return "error";
	    }else{
	    	 if( ((String) map.get("tableName")).startsWith("M_RFM")){
	   		  	 map.put("tableName", "M_RFM_model3");
	   	  	 }else if(((String) map.get("tableName")).startsWith("M_MagicQuadrant")){
	   	  		 map.put("tableName", "M_MagicQuadrant_cfg");
	   	  	 }
	    }

	    String token = this.powerBiTokenService.genToken(map);
	    if (token == null) {
	      mode.put("info", "token  生成失败!");
	      return "error";
	    }
	    mode.put("instanceId", instanceId);
	    mode.put("savePolicy", savePolicy);
	    mode.put("token", token);
	    mode.put("pbMap", map);
	    return "pb/reportmodel/pbapp";
	  }
  @RequestMapping(value={"/get/{instanceId}"}, method={RequestMethod.GET})
  public String getPowerbiHtml2(HttpServletRequest request, HttpServletResponse response, @PathVariable("instanceId") String instanceId, ModelMap mode)
  {
    Map<String, Object> map = this.reportModelService.getReportModelByInstanceId(instanceId);
    
    if (map == null) {
      mode.put("info", "输入的instanceID没找到相应的记录");
      return "error";
    }
    
    String token = this.powerBiTokenService.genToken(map);
    if (token == null) {
      mode.put("info", "token  生成失败!");
      return "error";
    }

    mode.put("token", token);
    mode.put("pbMap", map);
    return "pb/reportmodel/pbapp";
  }

  @RequestMapping(value={"/get/{instanceId}/{apitoken}"}, method={RequestMethod.GET})
  public String getPowerbiHtml(HttpServletRequest request, HttpServletResponse response, @PathVariable("instanceId") String instanceId, @PathVariable("apitoken") String apitoken, ModelMap mode)
  {
    apitoken =apitoken.replace("@", ".");
    logger.info("nifitoken:"+apitoken);
//    boolean isValid = this.powerBiTokenService.isValid(apitoken);
//    if (!isValid) {
//      mode.put("info", "请联系管理员，请求会话过期");
//      return "error";
//    }
    Map<String, Object> map = this.reportModelService.getReportModelByInstanceId(instanceId);
    if (map == null) {
      mode.put("info", "请联系管理员，输入的instanceID没找到相应的记录");
      return "error";
    }

    String token = this.powerBiTokenService.genToken(map);
    if (token == null) {
      mode.put("info", "token  生成失败!");
      return "error";
    }

    mode.put("token", token);
    mode.put("pbMap", map);
    return "pb/reportmodel/pbapp";
  }
  
  @RequestMapping(value={"/update/report/model"}, method={RequestMethod.POST})
  @ResponseBody
  public String updateReportModel(HttpServletRequest request, HttpServletResponse response, ReportModel model) { String reportID = this.powerBiService.getReportIdBydisplayName(model);
    if (reportID == null)
      return "fail";
    String result = this.reportModelService.updateReportModel(model, reportID);
    return result;
  }

  @RequestMapping(value={"/get/report/model/list"}, method={RequestMethod.POST})
  @ResponseBody
  public JSONObject getModelList(HttpServletRequest request, HttpServletResponse response, ReportModel model)
  {
    JSONObject jo = new JSONObject();
    JSONArray reports = this.powerBiService.getReportIdsBydisplayName(model);
    if (reports == null)
      jo.put("data", "fail");
    else {
      jo.put("data", reports);
    }
    return jo;
  }
  public static void main(String[] args) {
	System.out.println(createNewToken(appId));
  }
  public static final String appId="02bbdbef98dd406fadcbb21ee6dc62e3";
  public static String createNewToken(String appId) {
		// 获取当前时间
		Date now = new Date(System.currentTimeMillis());
		// 过期时间
		Date expiration = new Date(now.getTime() + 7200000 * 12);// 1天后过期
		return Jwts
				.builder()
				.setSubject(appId)
				// .claim(YAuthConstants.Y_AUTH_ROLES, userDbInfo.getRoles())
				.setIssuedAt(now).setIssuer("Online YAuth Builder")
				.setExpiration(expiration)
				.signWith(SignatureAlgorithm.HS256, "valleyAuthv1.0.0")
				.compact().replace(".", "@");
	}
  
}
